package com.bookshop.dao;

import com.bookshop.bean.AdminBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 专门操作admin表
 */

@Component
public class AdminDao {

    @Resource
    private JdbcTemplate jdbcTemplate;
    /**
     * 根据账号和密码查询管理员
     * @param account
     * @param pass
     * @return
     */
    public AdminBean selectByAccountAndPass(String account, String pass){
        String sql="SELECT admin_id,account,pass,nick_name FROM admins WHERE account=? AND pass=?";
        List<AdminBean> admins = new ArrayList<>();
        admins = jdbcTemplate.query(sql
                , new RowMapper<AdminBean>() {
                    @Override
                    public AdminBean mapRow(ResultSet rs,int rowNum)throws SQLException{
                        AdminBean admin = new AdminBean();
                        admin.setAdminId(rs.getInt("admin_id"));
                        admin.setAccount(rs.getString("account"));
                        admin.setPass(rs.getString("pass"));
                        admin.setNickName(rs.getString("nick_name"));
                        return admin;
                    }
                },account,pass);
        return admins == null || admins.size() == 0?null:admins.get(0);
    }

    public int updatePass(String pass,String account){
        String sql = "UPDATE admins SET pass=? WHERE account=?";
        return jdbcTemplate.update(sql,pass,account);
    }
}
